﻿using Dapper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using Xm.Entity;
using Xm.Models;

namespace Xm.Controllers
{
    public class engageController : Controller
    {
        private readonly ITestLogin _text; // 使用接口类型

        // 通过构造函数注入
        public engageController(ITestLogin text)
        {
            _text = text; // 初始化 text 对象
        }
        public IActionResult details()
        {
            return View();
        }
        
        public IActionResult list()
        {
            return View();
        }
        
         public IActionResult check()
        {
            return View();
        }
        public IActionResult check_list()
        {
            return View();
        }
       
        public IActionResult register()
        {
            return View();
        }
        
        public IActionResult register_list()
        {
            return View();
        }
        
        public IActionResult Index()
        {
            return View();
        }
        
        [HttpGet]
        public async Task<ActionResult<InterviewResumeViewModel>> cx()
        {
            try
            {
                // 调用服务层获取简历数据
                var result = await _text.cx();

                return Ok(result);
            }
            catch (System.Exception ex)
            {
                return StatusCode(500, "服务器错误: " + ex.Message);
            }
        }

        public IActionResult interview()
        {
            return View();
        }
        [HttpGet]
        public IActionResult engage_resume_Update()
        {
            return View();
        }
        [HttpPost]
        [Route("engage/engage_resume_Update")]
        public async Task<IActionResult> engage_resume_Update(engage_resume dz)
        {
            try
            {
                // 添加日志，确认方法是否被调用
                Console.WriteLine($"接收到插入请求: {JsonConvert.SerializeObject(dz)}");

                int i = await _text.UpdateInterviewAsync(dz);
                if (i > 0)
                {
                    return Ok(new { success = true, message = "添加成功" });
                }
                else
                {
                    return Ok(new { success = false, message = "插入失败" });
                }
            }
            catch (Exception ex)
            {
                // 添加异常处理，记录详细错误
                Console.WriteLine($"插入异常: {ex.Message}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }
        [HttpGet]
        public IActionResult engage_interview_add()
        {
            return View();
        }
        [HttpPost]
        [Route("engage/engage_interview_add")]
        public async Task<IActionResult> engage_interview_add(engage_interview dz)
        {
            try
            {
                // 添加日志，确认方法是否被调用
                Console.WriteLine($"接收到插入请求: {JsonConvert.SerializeObject(dz)}");

                int i = await _text.InsertInterviewAsync(dz);
                if (i > 0)
                {
                    return Ok(new { success = true, message = "添加成功" });
                }
                else
                {
                    return Ok(new { success = false, message = "插入失败" });
                }
            }
            catch (Exception ex)
            {
                // 添加异常处理，记录详细错误
                Console.WriteLine($"插入异常: {ex.Message}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }
        [HttpGet]
        public async Task<IActionResult> Updateengage_resume()
        {

            return View();
        }
        [HttpPost]
        [HttpPut] // 同时支持POST和PUT
        [Route("engage/Updateengage_resume")]
        public async Task<IActionResult> Updateengage_resume([FromBody] engage_resume dz) // 修正类型
        {
            try
            {
                if (dz == null)
                {
                    return BadRequest(new { success = false, message = "数据为空" });
                }

                // 判断是新增还是修改（根据fsk_id是否有值）
                bool isUpdate = dz.res_id > 0;
                int result = 0;

                if (isUpdate)
                {
                    result = await _text.Updateengageresume1(dz); // 修改操作
                }
                else
                {
                    // 新增操作（需要在_text中添加对应的新增方法）
                    result = await _text.Updateengageresume1(dz);
                }

                return result > 0
                    ? Ok(new { success = true, message = isUpdate ? "修改成功" : "新增成功" })
                    : Ok(new { success = false, message = isUpdate ? "修改失败" : "新增失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新异常: {ex.ToString()}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }
        //[HttpGet]
        //public async Task<IActionResult> Updateengage_resume()
        //{

        //    return View();
        //}
        //[HttpPost] // 确保使用HttpPost属性
        //[Route("engage/Updateengage_resume")]
        //public async Task<IActionResult> Updateengage_resume([FromBody] engage_resume dz)
        //{
        //    if (dz == null)
        //    {
        //        return BadRequest(new { success = false, message = "数据为空或格式错误" });
        //    }

        //    if (ModelState.IsValid)
        //    {
        //        int result = await _text.Updateengageresume1(dz);
        //        return Ok(new { success = result > 0, message = result > 0 ? "更新成功" : "更新失败，请重试" });
        //    }
        //    else
        //    {
        //        var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
        //        return BadRequest(new { success = false, message = "验证失败", errors });
        //    }
        //}
        public IActionResult sx()
        {
            return View();
        }
        public IActionResult resumechoosecx()
        {
            return View();
        }
        [HttpGet]
        public async Task<ActionResult<engage_resume>> GetResumes(
           string humanMajorKindName,
           string humanMajorName,
           string humanName,
           DateTime? startDate,
           DateTime? endDate
           )
        {
            try
            {
                // 调用服务层获取简历数据
                var result = await _text.SearchResume(
                    humanMajorKindName,
                    humanMajorName,
                    humanName,
                    startDate,
                    endDate
                   );

                return Ok(result);
            }
            catch (System.Exception ex)
            {
                return StatusCode(500, "服务器错误: " + ex.Message);
            }
        }
    
        public IActionResult Updatefy(int currentPage, int pageSize)
        {
            //调用分页的存储过程
            string connectionStr = "server=.;database=HR_DB;uid=sa;pwd=123456;";
            using (SqlConnection conn = new SqlConnection(connectionStr))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@tableName", "res_id");
                param.Add("@keyName", "engage_resume");
                param.Add("@currentPage", currentPage);
                param.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYe] @pageSize, @tableName, @keyName, @currentPage, @rows out";
                List<engage_resume> list = conn.Query<engage_resume>(sql, param).ToList();

                FenYe<engage_resume> fenYecs = new FenYe<engage_resume>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("rows");
                //return fenYecs;
                return Json(fenYecs);
            }


        }
        
         public IActionResult interviewlist()
        {
            return View();
        }
        public IActionResult resumeregister()
        {
            return View();
        }
        [HttpGet] // 添加明确的路由
        public async Task<IActionResult> GetJobCascaderData()
        {
            try
            {
                // 直接返回服务层处理好的数据，无需再次转换
                var cascaderData = await _text.GetJobCascaderDataAsync();   
                return Ok(cascaderData);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取职位级联数据失败: {ex.Message}");
                return StatusCode(500, "获取职位数据失败");
            }
        }
        public IActionResult resumechoose()
        {
            return View();
        }
        public IActionResult engage_resume()
        {
            return View();
        }
        [HttpGet]
        public IActionResult engage_resume_add()
        {
            return View();
        }
        [HttpPost]
        [Route("engage/engage_resume_add")]
        public async Task<IActionResult> engage_resume_add( engage_resume dz)
        {
            try
            {
                // 添加日志，确认方法是否被调用
                Console.WriteLine($"接收到插入请求: {JsonConvert.SerializeObject(dz)}");

                int i = await _text.engage_resumeInsert(dz);
                if (i > 0)
                {
                    return Ok(new { success = true, message = "添加成功" });
                }
                else
                {
                    return Ok(new { success = false, message = "插入失败" });
                }
            }
            catch (Exception ex)
            {
                // 添加异常处理，记录详细错误
                Console.WriteLine($"插入异常: {ex.Message}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }

    }
}
